package cn.bocai.pc.web.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.bocai.pc.model.BcLinktble;
import cn.bocai.pc.service.BcDrawingService;
import cn.bocai.pc.service.BcLinktbleService;
import cn.bocai.pc.service.BcThumpicService;
import cn.bocai.pc.service.VariableService;
import cn.bocai.pc.util.PCConstants;
import cn.bocai.pc.util.UploadResponse;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
/** 
 * @className: BcUploadController
 * @description: 上传图片
 * @author: 99fu
 * @date: 2015年06月26日 下午6:20:31
 * @explain :多种方法处理上图片
 * @修改人：
 * @修改时间：
 * @修改内容：
 */
@Controller
@RequestMapping("/upload")
public class BcUploadController {
	@Autowired
	private BcThumpicService bcThumpicService;
	@Autowired
	private VariableService variableService;
	@Autowired
	private BcDrawingService bcDrawingService;
	@Autowired
	private BcLinktbleService bcLinktbleService;

	//plupload 上传所需常量
    private static final String RESP_SUCCESS = "{\"jsonrpc\" : \"2.0\", \"result\" : \"success\", \"id\" : \"id\"}";   
    private static final String RESP_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";   
    public static final String JSON = "application/json";   
    public static final int BUF_SIZE = 2 * 1024;   
    public static final String FileDir = "uploadfile/";   
    private int chunk;   
    private int chunks;   
    private String name;   
    private String user;   
    private String time; 
	/**
	 * 通过jquary的ajax请求，form提交方式上传
	 * @param request
	 * @param fileName
	 * @return out
	 * @author 99fu
	 * @time 2015年6月26日13:04:11
	 */
	@RequestMapping("/uploadPic.do")
	public void uploadPic(HttpServletRequest request, String fileName,
			PrintWriter out) {
		 String PicUrl = variableService.selectVariable("PIC_bigUrl");
		MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
		CommonsMultipartFile cfile = (CommonsMultipartFile) mr
				.getFile(fileName);
		byte[] ftype = cfile.getBytes();
		String tfileName = "";
		tfileName = new SimpleDateFormat("yyyyMMddHHmmssSSS")
				.format(new Date());
		Random random = new Random();
		for (int i = 0; i < 3; i++) {
			tfileName = tfileName + random.nextInt(10);
		}
		String suffix = "";
		String orgFileName = cfile.getOriginalFilename();
		suffix = orgFileName.substring(orgFileName.lastIndexOf("."));
		// 创建jersy客户端
		Client client = Client.create();
		// 指定图片服务器上的图片路径
		WebResource wr = client.resource(PicUrl + "/"
				+ tfileName + suffix);
		// 直接上传图片到另一台主机
		wr.put(String.class, ftype);
		String realPath = PicUrl+ "/" + tfileName
				+ suffix;
		String raltivePath = "/" + tfileName + suffix;
		// {"realPath":"http;///"}
		String result = "{\"realPath\":\"" + realPath
				+ "\", \"raltivePath\":\"" + raltivePath + "\"}";
		out.write(result);

	}
	/**
	 * 通过FCK提交方式上传
	 * @param request
	 * @param fileName
	 * @return out
	 * @author 99fu
	 * @time 2015年6月26日13:04:11
	 */
	@RequestMapping("/uploadForFck.do")
	public void uploadForFck(HttpServletRequest request, String fileName,
			PrintWriter out) {
		MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> map = mr.getFileMap();
		Set<String> set = map.keySet();
		String key = set.iterator().next();
		CommonsMultipartFile cfile = (CommonsMultipartFile) map.get(key);
		byte[] ftype = cfile.getBytes();
		String tfileName = "";
		tfileName = new SimpleDateFormat("yyyyMMddHHmmssSSS")
				.format(new Date());
		Random random = new Random();
		for (int i = 0; i < 3; i++) {
			tfileName = tfileName + random.nextInt(10);
		}
		String suffix = "";
		String orgFileName = cfile.getOriginalFilename();
		suffix = orgFileName.substring(orgFileName.lastIndexOf("."));
		// 创建jersy客户端
		Client client = Client.create();
		// 指定图片服务器上的图片路径
		WebResource wr = client.resource(PCConstants.PIC_HOST + "/upload/"
				+ tfileName + suffix);
		// 直接上传图片到另一台主机
		wr.put(String.class, ftype);
		String realPath = PCConstants.PIC_HOST + "/upload/" + tfileName
				+ suffix;
		UploadResponse ur = new UploadResponse(UploadResponse.EN_OK, realPath);
		out.print(ur);

	}
	
	/**
	 * 通过plupload前台插件,多文件上传
	 * @param request
	 * @param fileName
	 * @return out
	 * @author 99fu
	 * @throws IOException 
	 * @time 2015年6月26日13:04:11
	 */
	@RequestMapping("/fileUpload")
	public void fileUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		 String responseString = RESP_SUCCESS;   
	        boolean isMultipart = ServletFileUpload.isMultipartContent(req);   
	        if(isMultipart){   
	            ServletFileUpload upload = new ServletFileUpload();   
	            try {   
	                FileItemIterator iter = upload.getItemIterator(req);   
	                while (iter.hasNext()) {   
	                    FileItemStream item = iter.next();   
	                    InputStream input = item.openStream();   
	                    // Handle a form field.   
	                    if(item.isFormField()){   
	                        String fileName = item.getFieldName();   
	                        String value = Streams.asString(input);   
	                        if("name".equals(fileName)){   
	                            this.name = value;   
	                        }else if("chunks".equals(fileName)){   
	                            this.chunks = Integer.parseInt(value);   
	                        }else if("chunk".equals(fileName)){   
	                            this.chunk = Integer.parseInt(value);   
	                        }else if("user".equals(fileName)){   
	                            this.user = value;   
	                        }else if("time".equals(fileName)){   
	                            this.time = value;   
	                        }   
	                    }   
	                    // Handle a multi-part MIME encoded file.   
	                    else {   
	                        String fileDir = req.getSession().getServletContext().getRealPath("/")+FileDir;   
	                        File dstFile = new File(fileDir);   
	                        if (!dstFile.exists()){   
	                            dstFile.mkdirs();   
	                        }   
	                        File dst = new File(dstFile.getPath()+ "/" + this.name);   
	                        saveUploadFile(input, dst);   
	  
	                    }   
	  
	                }   
	  
	            }   
	            catch (Exception e) {   
	                responseString = RESP_ERROR;   
	                e.printStackTrace();   
	            }   
	        }   
	        // Not a multi-part MIME request.   
	        else {   
	            responseString = RESP_ERROR;   
	        }   
	        if(this.chunk == this.chunks - 1){   
	            System.out.println("用户："+this.user);   
	            System.out.println("文件名称："+this.name);   
	            System.out.println("上传时间："+this.time);  
	        }   
	  
	        resp.setContentType(JSON);   
	        byte[] responseBytes = responseString.getBytes();   
	        resp.setContentLength(responseBytes.length);   
	        ServletOutputStream output = resp.getOutputStream();   
	        output.write(responseBytes);   
	        output.flush();   
	}
	
	 private void saveUploadFile(InputStream input, File dst) throws IOException {   
	        OutputStream out = null;   
	        try {   
	            if (dst.exists()) {   
	                out = new BufferedOutputStream(new FileOutputStream(dst, true),   
	                        BUF_SIZE);   
	            } else {   
	                out = new BufferedOutputStream(new FileOutputStream(dst),   
	                        BUF_SIZE);   
	            }   
	            byte[] buffer = new byte[BUF_SIZE];   
	            int len = 0;   
	            while ((len = input.read(buffer)) > 0) {   
	                out.write(buffer, 0, len);   
	            }   
	        } catch (Exception e) {   
	            e.printStackTrace();   
	        } finally {   
	            if (null != input) {   
	                try {   
	                    input.close();   
	                } catch (IOException e) {   
	                    e.printStackTrace();   
	                }   
	            }   
	  
	            if (null != out) {   
	                try {   
	                    out.close();   
	                } catch (IOException e) {   
	                    e.printStackTrace();   
	                }   
	            }   
	  
	        }   
	  
	    }   
	 
	 
		/**
		 * 图片上传
		 * @param fileName
		 * @param request
		 * @throws Exception 
		 */
		@RequestMapping("/uploadPicOne.do")
		public void uploadPic(String fileName,String colourType, HttpServletRequest request,HttpServletResponse response, PrintWriter out) throws Exception{
		    //http://localhost:8081/thumb/
			String FileExist=variableService.selectVariable("PIC_FileExist");//获取图片服务器的图片上传地址
			//D:/picture
			String PicBigUrl=variableService.selectVariable("PIC_bigUrl");//获取图片服务器的图片存放磁盘目录
 			MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
 			//获得文件
 			CommonsMultipartFile cfile =  (CommonsMultipartFile) mr.getFile(fileName);
 			if (cfile == null) {
                throw new Exception("上传失败：文件为空");    
            }
            if(cfile.getSize()>10000000){
                throw new Exception("上传失败：文件大小不能超过10M");            
            }
 			byte[] bfile = cfile.getBytes();
 			String oriFName = cfile.getOriginalFilename();
 			String url=FileExist+colourType+"/"+oriFName;
 			
 			//查看图片是否存在，存在就删除，
 			String fileCheckout = bcThumpicService.fileCheckout(PicBigUrl+"/thumb/"+colourType+"/"+oriFName);
 			String result = "";
 			if("ok".equals(fileCheckout)){
 				//创建图片上传的客户端
 	 			Client client = Client.create();
 	 			//指定图片的在图片服务器上的完整路径
 	 			WebResource resource = client.resource(url);
 	 			//把图片上传到图片服务器
 	 			resource.put(String.class, bfile);
 	 		    //查询出一共多少条数
				int rowCountCol = bcThumpicService.searRowAll("1");
				int rowCountBlack = bcThumpicService.searRowAll("0");
 	 			//{\"a\":\"b\",\"c\":\"d\"}
 	 		    result = "{\"relativePath\":\"/thumb/"+colourType+"/"+oriFName+"\", \"path\":\""+FileExist+colourType+"/"+oriFName+"\",\"numbers\":\""+rowCountCol+"_"+rowCountBlack+"\"}";
 			}
 			out.write(result);
		}
	 
		/**
		 * 全年图纸上传
		 * @param fileName
		 * @param request
		 * @throws Exception 
		 */
		@RequestMapping("/uploadDrawPic.do")
		public void drawUpload(String fileName,String name, HttpServletRequest request,HttpServletResponse response, PrintWriter out) throws Exception{
			String year=request.getParameter("years");
			// 到数据字典去查询出对应的值
			String draUrl = variableService.selectVariable("DRA_UEL");// /drawPic
			String baUrl = variableService.selectVariable("BA_URL");// http://localhost:8081
			String backdir = variableService.selectVariable("Draw_UEL");// D:/
			
 			MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
 			//获得文件
 			CommonsMultipartFile cfile =  (CommonsMultipartFile) mr.getFile(fileName);
 			if (cfile == null) {
                throw new Exception("上传失败：文件为空");    
            }
            if(cfile.getSize()>10000000){
                throw new Exception("上传失败：文件大小不能超过10M");            
            }
 			byte[] bfile = cfile.getBytes();
 			String oriFName = cfile.getOriginalFilename();//图片名称
 			String suffix = oriFName.substring(0,oriFName.lastIndexOf("."));
 			String result = "";
 			if(name.equals(suffix)){
 				String url=baUrl+draUrl+"/"+year+"/"+oriFName;
 	 			//查看图片是否存在，存在就删除，
 	 			String fileCheckout = bcThumpicService.fileCheckout(backdir+"drawPic/"+year+"/"+oriFName);
 	 			
 	 			if("ok".equals(fileCheckout)){
 	 				//创建图片上传的客户端
 	 	 			Client client = Client.create();
 	 	 			//指定图片的在图片服务器上的完整路径
 	 	 			WebResource resource = client.resource(url);
 	 	 			//把图片上传到图片服务器
 	 	 			resource.put(String.class, bfile);
 	 	 			//{\"a\":\"b\",\"c\":\"d\"}
 	 	 		    result = "{\"state\":\"succend\",\"relativePath\":\"/"+year+"/"+oriFName+"\", \"path\":\""+url+"\"}";
 	 			}
 			}else{
 				result = "{\"state\":\"failure\"}";
 			}
 			out.write(result);
		}	
		
		
		/**
		 * 彩票、真人、游戏图片上传
		 * @param fileName
		 * @param request
		 * @throws Exception 
		 */
		@RequestMapping("/uploadFourPic.do")
		public void uploadFourPic(String fileName, HttpServletRequest request,HttpServletResponse response, PrintWriter out,String type,String id) throws Exception{
		    //http://localhost:8081/other
			String FileExist=variableService.selectVariable("Link_FourUrl");//获取图片服务器的图片上传地址
			//D:/other
			String PicBigUrl=variableService.selectVariable("LINK_FourAddress");//获取图片服务器的图片存放磁盘目录
 			MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
 			//获得文件
 			CommonsMultipartFile cfile =  (CommonsMultipartFile) mr.getFile(fileName);
 			if (cfile == null) {
                throw new Exception("上传失败：文件为空");    
            }
            if(cfile.getSize()>10000000){
                throw new Exception("上传失败：文件大小不能超过10M");            
            }
 			byte[] bfile = cfile.getBytes();
 			String oriFName = cfile.getOriginalFilename();
 			String url=FileExist+"/four"+"/"+oriFName;
 			
 			//查看图片是否存在，存在就删除，
 			String fileCheckout = bcThumpicService.fileCheckout(PicBigUrl+"/four/"+oriFName);
 			String result = "";
 			if("ok".equals(fileCheckout)){
 				//创建图片上传的客户端
 	 			Client client = Client.create();
 	 			//指定图片的在图片服务器上的完整路径
 	 			WebResource resource = client.resource(url);
 	 			//把图片上传到图片服务器
 	 			resource.put(String.class, bfile);
 	 		    //查询出一共多少条数
				/*int rowCountCol = bcThumpicService.searRowAll("1");
				int rowCountBlack = bcThumpicService.searRowAll("0");*/
 	 			//{\"a\":\"b\",\"c\":\"d\"}
 	 		    result = "{\"relativePath\":\"/four/"+oriFName+"\", \"path\":\""+url+"\"}";
	 	 		  if(type.equals("upd")){
	 	 			  BcLinktble bcLinktble = new BcLinktble();
	 	 			updateFourTa(id,bcLinktble,"/four/"+oriFName);
		 		   }
 			}
 			out.write(result);
		}
		//当修改图片的时候也要修改数据库保存的这个数据
		public void updateFourTa(String id,BcLinktble reTable,String url){
				reTable.setId(id);
				reTable.setSkipAddress(url);
			    bcLinktbleService.updateByPrimaryKeySelective(reTable);
		}
}
